import router from 'umi/router';
import store from 'store';
import storage from '@/utils/storage';
import routeList from '@/utils/routes';
import { notiSuccess } from '@/utils/notification';
import { signInService, signUpService } from '@/services/api';
import { messErr } from '@/utils/message';


export default {
  namespace: 'app',
  state: {
    // user: {
    //   id: 10,
    //   username: '18627825090',
    //   token: 'dansdaslhdkajhfbgdf',
    // },
    user: null,
    routeList,
    locationPathname: '',
    locationQuery: {},
    theme: 'light',
    openKeys: [
      'zhongzhijishu',
      'zhongzhiguanli',
      'jixiexinxi',
      'jixieguanli',
      'zhongzhijishu_anpinzhongfenpei',
      'zhongzhijishu_anshijianfenpei',
      'jixieguanli_guanlijuece',
      'jixiexinxi_youcainongji',
      'jixiexinxi_nongjinongyi',
    ], // 侧边栏菜单打开状态的 keys
  },
  subscriptions: {
    setupHistory({ dispatch, history }) {
      history.listen(location => {
        console.log('????');

        // 页面跳转的时候检查用户是否已经登录
        if(location.pathname !== '/login') {
          dispatch({
            type: 'checkUserLoggedInEffect',
          });
        }

        dispatch({
          type: 'updateState',
          payload: {
            locationPathname: location.pathname,
            locationQuery: location.query,
          },
        });
      });
    },
  },
  effects: {
    // 检查用户是否已经登录，没有登录则跳转到登录页面去
    * checkUserLoggedInEffect(_, { select, put }) {
      // 判定用户的身份信息
      const userInfo = store.get(storage.user) || null;
      if(!userInfo) {
        router.push('/login');
      }
      yield put({
        type: 'applyUser',
        payload: userInfo,
      });
    },
    // 退出登录状态
    * logoutEffect(_, { put }) {
      store.remove(storage.user);
      router.push('/login');
      notiSuccess('已经成功退出登录！');
      yield put({
        type: 'logoutReducer'
      });
    },
    * signInEffect({ payload: { data } }, { call, put }) {
      const response = yield call(signInService, data);

      if (response && !response.errno && response.data) {
        // 登录成功之后的操作
        const rdata = response.data;
        const user = {
          id: rdata.id,
          token: rdata.token,
          username: rdata.username,
        };

        yield put({
          type: 'signInReducer',
          payload: user,
        });
        store.set(storage.user, user);
        console.log(user);

        router.push({
          pathname: '/',
        });
      } else {
        // 登录失败之后，提示用户用户名或密码错误
        messErr(response.errmsg);
      }
    },
    * signUpEffect({ payload: { data } }, { call, put }) {
      const response = yield call(signUpService, data);

      if (response && !response.errno && response.data) {
        // 注册成功之后的操作
        const rdata = response.data;
        const user = {
          id: rdata.id,
          token: rdata.token,
          username: rdata.username,
        };

        yield put({
          type: 'signInReducer',
          payload: user,
        });
        store.set(storage.user, user);
        router.push({
          pathname: '/',
        });

      } else {
        // 登录失败之后，提示用户用户名或密码错误
        messErr(response.errmsg);
      }
    },

  },
  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    signInReducer(state, { payload }) {
      return {
        ...state,
        user: {
          ...payload,
        },
      };
    },
    logoutReducer(state) {
      return {
        ...state,
        user: null,
      };
    },
    applyUser(state, { payload }) {
      return {
        ...state,
        user: {
          ...payload,
        },
      };
    },
  },
};
